<template>
  <Layout>
    <Row>
      <Card dis-hover>
        <h3>
          {{ taskInfo.taskName }}
        </h3>
        <ButtonGroup slot="extra" v-if="!taskInfo.viewFlag">

          <Button @click="submitAndUpdate('showdata')" type="warning" style="background: #EF5350;"
                  :loading="buttonloading1" v-if="taskInfo.procinstState === '2'">
            <Icon type="ios-bookmark"/>
            审批
          </Button>
          <Button @click="submit('showdata')" type="warning" style="background: #EF5350;" :loading="buttonloading1"
                  v-else>
            <Icon type="ios-bookmark"/>
            审批
          </Button>

          <Button @click="returnTo">
            返回
            <Icon type="ios-arrow-forward"/>
          </Button>
        </ButtonGroup>
        <ButtonGroup slot="extra" v-else>
          <Button @click="returnTo">
            返回
            <Icon type="ios-arrow-forward"/>
          </Button>
        </ButtonGroup>

      </Card>

      <i-col>
        <Card dis-hover style="margin-top: 10px">
          <div :style="{ overflowY: 'auto'}" v-if="taskInfo.procinstState === '2'">
            <Col span="18">
              <Form :model="showdata" ref="showdata" :rules="ruleCustom" :label-width="160">
                <Row type="flex" justify="space-around" class="code-row-bg">
                  <Col span="11">
                    <FormItem label="审计任务：" prop="missionName">
                      <Input class='' type='text' v-model='showdata.missionName' readonly></Input>
                    </FormItem>
                  </Col>
                  <Col span="11">
                    <FormItem label="被审计单位：" prop="auditOrgName">
                      <Input class='' type='text' v-model='showdata.auditOrgName' readonly></Input>
                    </FormItem>
                  </Col>

                </Row>
                <Row type="flex" justify="space-around" class="code-row-bg">
                  <Col span="11">
                    <FormItem label="开始时间：" prop="startDate">
                      <Date-picker type="date" v-model="showdata.startDate" placeholder="选择日期"
                                   style="width: 100%"></Date-picker>
                    </FormItem>
                  </Col>
                  <Col span="11">
                    <FormItem label="结束时间：" prop="endDate">
                      <Date-picker type="date" v-model="showdata.endDate" placeholder="选择日期"
                                   style="width: 100%"></Date-picker>
                    </FormItem>
                  </Col>
                </Row>
                <Row type="flex" justify="space-around" class="code-row-bg">
                  <Col span="11">
                    <FormItem label="上报人：" prop="userName">
                      <Input class='' type='text' v-model='showdata.userName' readonly></Input>
                    </FormItem>
                  </Col>
                  <Col span="11">
                    <FormItem label="上报人电话：" prop="userPhone">
                      <Input class='' type='text' v-model='showdata.userPhone'></Input>
                    </FormItem>
                  </Col>
                </Row>
                <Row type="flex" justify="space-around">
                  <Col span="23">
                    <FormItem label="概述：" prop="desc">
                      <Input v-model="showdata.desc" type="textarea" :rows="2"/>
                    </FormItem>
                  </Col>
                </Row>

                <Row type="flex" justify="space-around" class="code-row-bg">
                  <Col span="23">
                    <FormItem label="计划附件：">
                      <FileUpload :upload="true" :id="showdata.id" uri="adtReport"/>
                    </FormItem>
                  </Col>
                </Row>
              </Form>
            </Col>
          </div>
          <div :style="{ overflowY: 'auto'}" v-else>
            <Col span="24">
              <Form :model="showdata" ref="showdatas" :rules="ruleCustom1" :label-width="160">
                <Row type="flex" justify="space-around" class="code-row-bg">
                  <Col span="11">
                    <FormItem label="审计任务：" prop="missionName">
                      {{ showdata.missionName }}
                    </FormItem>
                  </Col>
                  <Col span="11">
                    <FormItem label="被审计单位：" prop="auditOrgName">
                      {{ showdata.auditOrgName }}
                    </FormItem>
                  </Col>

                </Row>
                <Row type="flex" justify="space-around" class="code-row-bg">
                  <Col span="11">
                    <FormItem label="开始时间：" prop="startDate">
                      {{ renderViewDate(showdata.startDate) }}
                    </FormItem>
                  </Col>
                  <Col span="11">
                    <FormItem label="结束时间：" prop="endDate">
                      {{ renderViewDate(showdata.endDate) }}
                    </FormItem>
                  </Col>

                </Row>
                <Row type="flex" justify="space-around" class="code-row-bg">
                  <Col span="11">
                    <FormItem label="上报人：" prop="userName">
                      {{ showdata.userName }}
                    </FormItem>
                  </Col>
                  <Col span="11">
                    <FormItem label="上报人电话：" prop="userPhone">
                      {{ showdata.userPhone }}
                    </FormItem>
                  </Col>

                </Row>
                <Row type="flex" justify="space-around">
                  <Col span="23">
                    <FormItem label="概述：" prop="desc">
                      {{ showdata.desc }}
                    </FormItem>
                  </Col>
                </Row>
                <Row type="flex" justify="space-around">
                  <Col span="23">
                    <FormItem label="计划附件：">
                      <FileUpload :upload="false" :id="showdata.id" uri="adtReport"/>
                    </FormItem>
                  </Col>
                </Row>

                <Row v-if="!taskInfo.viewFlag">
                  <Col span="11">
                    <FormItem label="审批结果：" prop="route">
                      <Select v-model="showdata.route" @on-change="routePush">
                        <Option v-for="item in approveList" :value="item.value" :key="item.value">{{
                            item.text
                          }}
                        </Option>
                      </Select>
                    </FormItem>
                  </Col>

                </Row>
                <Row v-if="!taskInfo.viewFlag">
                  <Col span="11">
                    <FormItem label="处理意见：" prop="opinion">
                      <Input v-model="showdata.opinion" type="textarea" :rows="2"/>
                    </FormItem>
                  </Col>
                </Row>

              </Form>
            </Col>
          </div>
        </Card>
      </i-col>
    </Row>
  </Layout>
</template>


<script>
import {Api} from '../../../api/index.js'
import cascaderDom from "../../../components/cascader-dom.vue"
import {formatDate} from "@/tools";
import FileUpload from '@/views/safe/audit/FileUpload.vue'

export default {
  components: {
    cascaderDom, FileUpload
  },
  data() {
    return {
      uploadList: [],
      user: {},
      taskInfo: {},
      uploadListVisible: [],
      uploadListPercent: [],
      fileUrl: Api.interestedPartiesUserFile,
      pageModel2: {
        total: 0,
        pageSize: 10,
        currentPage: 1,
        contractorName: ''
      },
      options: {
        disabledDate(date) {
          return date && date.valueOf() <= Date.now();
        },
      },
      contractor: [],
      pageSizeArray: [10, 20, 50],
      evaluationPeriodDate: [null, null],
      contractTermDate: [null, null],
      evaluationPeriodDate1: null,
      contractTermDate1: null,
      viewFlag: false,
      flag: false,
      buttonloading1: false,
      approveFlag: '',
      approveList: [
        {
          text: "通过",
          value: "1"
        },
        {
          text: "不通过",
          value: "2"
        }
      ],
      showdata: {},
      tableHeight: 450,
      file: null,
      fileName: null,
      downloadUrl: Api.downloadMongoFile,
      formList: [],
      ruleCustom1: {
        opinion: [{
          validator: (rule, value, callback) => {
            if (this.showdata.opinion == undefined || this.showdata.opinion == null || this.showdata.opinion == '') {
              callback(' ')
            } else {
              callback()
            }
          },
          required: true,
          trigger: 'change'
        }],
        route: [
          {required: true, message: '  ', trigger: 'blur'}
        ]
      },
      ruleCustom: {
        missionName: [
          {required: true, message: '  ', trigger: 'change'}
        ],
        auditOrgName: [
          {required: true, message: '  ', trigger: 'change'}
        ],
        startDate: [
          {required: true, message: '  ', trigger: 'change', type: 'date'}
        ],
        endDate: [
          {required: true, message: '  ', trigger: 'change', type: 'date'}
        ],
        userName: [
          {required: true, message: '  ', trigger: 'change'}
        ],
        userPhone: [{
          validator: (rule, value, callback) => {
            if (!(/^1[3456789]\d{9}$/.test(this.showdata.userPhone))) {
              callback(' ');
              // this.$Message.error("请填写有效的的手机号")
            } else {
              callback()
            }
          },
          required: true,
          trigger: 'blur'
        }],
        opinion: [{
          validator: (rule, value, callback) => {
            if (this.showdata.opinion == undefined || this.showdata.opinion == null || this.showdata.opinion == '') {
              callback(' ')
            } else {
              callback()
            }
          },
          required: true,
          trigger: 'change'
        }],
        route: [
          {required: true, message: '  ', trigger: 'blur'}
        ]
      }
    }
  },
  mounted() {
    let _this = this;
    if (this.$route.query.close == false) {
      this.$http.get(Api.getUserByUserId + this.$route.query.userId)
          .then(function (res) {
            _this.user = res.data.data;
            _this.$http.get(Api.getTaskData + "/" + this.$route.query.procinstId + "/" +
                _this.$route.query.taskId + "?close=" + this.$route.query.close).then(function (res1) {
              this.taskInfo = res1.data;
              if (res1.data.viewFlag == false)
                _this.taskInfo.viewFlag = false;
              else
                _this.taskInfo.viewFlag = true;
              _this.query();
              return;
            })
          })
    } else {
      var search = window.location.href.split('?')[1];//截取URL？后面的参数
      var params = {};
      if (search != "" && search != undefined) {
        search.split("&").forEach(
            function (val) {
              var arr = val.split("=");
              params[arr[0]] = arr[1];
            }
        )
      }
      var code = params.code
      var status = params.status
      if (code != null && code != 'undefine') {
        this.$http.get(Api.queryToken, {
          params: {
            code: code,
          }
        }).then(res1 => {
          if (res1.data.errcode == "1014") {
            this.$http.get(Api.getReZheng).then(res2 => {
              window.location.href = decodeURIComponent(res2.bodyText) + "&redirect_uri=" + encodeURIComponent(window.location.href);
            })
          } else {
            this.$http.get(Api.getUserByUserId + this.$route.query.userId)
                .then(function (res) {
                  this.user = res.data.data;
                  this.$http.get(Api.getTaskData + "/" + this.$route.query.procinstId + "/" +
                      this.$route.query.taskId + "?close=" + this.$route.query.close).then(function (res1) {
                    this.taskInfo = res1.data;
                    if (res1.data.viewFlag == false)
                      this.taskInfo.viewFlag = false;
                    else
                      this.taskInfo.viewFlag = true;
                    this.query();
                    return;
                  })
                })
          }
        })
      } else {
        this.$http.get(Api.getReZheng).then(res2 => {
          window.location.href = decodeURIComponent(res2.bodyText) + "&redirect_uri=" + encodeURIComponent(window.location.href);
        });
      }
    }
  },
  methods: {
    renderViewDate(date) {
      if (!date) return "";
      return formatDate(new Date(date), "yyyy-MM-dd");
    },
    downloadFiles(file, index) {
      let url = this.fileUrl + '/file/' + file.id;
      this.uploadListVisible[index] = true;
      this.uploadListVisible[file.id] = true;
      var _this = this;
      this.$http.get(url, {
        responseType: 'blob',      //告诉服务器我们需要的响应格式
        progress: function (e) {
          _this.$set(_this.uploadListPercent, index, 100 * (e.loaded / e.total));
        }
      }).then((res) => {
        const aLink = document.createElement("a");
        let blob = new Blob([res.data], {
          type: res.bodyBlob.type      //将会被放入到blob中的数组内容的MIME类型
        });
        aLink.href = URL.createObjectURL(blob)
        aLink.download = file.fileName //标题
        aLink.click()
        document.body.appendChild(aLink)
      })
    },
    returnTo() {
      if (this.taskInfo.close == true)
        window.close();
      else
        this.$router.go(-1);
    },
    routePush(value) {
      if (value === '1') {
        this.showdata.opinion = "同意";
      } else {
        this.showdata.opinion = null;
      }
    },
    remove1(id) {
      let istrue = confirm("是否删除该文件？");
      if (istrue) {
        let url = this.fileUrl + '/file/' + id;
        this.$http.delete(url).then((res) => {
          this.getFiles()
        })
      }

    },

    beforeUpload(file) {
      let formData = new FormData();
      formData.append("files", file); // 文件对象
      let url = this.fileUrl + '/' + this.showdata.reportId + '/files/adtReport'
      this.$http.post(url, formData).then((res) => {
        if (res.data.result == "success") {
          this.$Message.info("文件上传成功")
          this.getFiles();
        }
      })
      return false
    },
    getFiles() {
      let url = this.fileUrl + '/' + this.showdata.reportId + '/files/adtReport'
      this.$http.get(url).then((res) => {
        if (res.data.result == "success") {
          this.uploadList = res.data.data
          console.log(this.uploadList);
        }
      })
    },
    setApproveUserName(data) {
      this.showdata.approveUserName = data;
    },
    setApproveUserId(data) {
      this.showdata.approveUserId = data[data.length - 1];
    },

    setApproveUserName1(data) {
      this.showdata.approveUserName = data;
    },
    setApproveUserId1(data) {
      let userId = "";
      for (let i = 0; i < data.length; i++) {
        userId += data[i]['value'] + ',';
      }
      this.showdata.approveUserId = userId;
    },
    downloadFile(perfId, file) {

      let url = Api.interestedPartiesUserFile + '/file/' + file.id;
      this.$http.get(url, {
        responseType: 'blob'      //告诉服务器我们需要的响应格式
      }).then((res) => {
        console.log(res)
        const aLink = document.createElement("a");
        let blob = new Blob([res.data], {
          type: res.bodyBlob.type      //将会被放入到blob中的数组内容的MIME类型
        });
        aLink.href = URL.createObjectURL(blob)
        aLink.download = file.fileName //标题
        aLink.click()
        document.body.appendChild(aLink)
      })
    },
    danxuan(row, index) {
      this.showdata.contractorId = row.contractorId
      this.showdata.contractorName = row.contractorName
      this.model2 = false

    },
    async query() {
      let url = Api.getAdtRectification;
      let id = this.taskInfo.workId;
      let _this = this;
      await this.$http.get(url, {params: {id: id}}).then((res) => {
        if (res.data.status === 200) {
          _this.showdata = res.data.data;
          _this.id = _this.showdata.id;
        }
      }).catch(e => {
        this.$Message.error("数据获取失败")
      })
    },
    pageSizeChange1(pageSize) {
      this.pageModel2.pageSize = pageSize;
      this.query();
    },
    submitAndUpdate() {
      this.$refs['showdata'].validate((valid) => {
        if (valid) {
          this.buttonloading1 = true;
          let data = {};
          data = {
            createUserId: this.user.userId,
            userName: this.user.userName,
            opinion: this.showdata.opinion,
            formKey: 'rectificationPlanForApproval',
            taskId: this.taskInfo.taskId,
            workId: this.taskInfo.workId,
            procinstId: this.taskInfo.procinstId,
          };
          let url = Api.updateAdtRectification;
          this.showdata.updateUserId = this.user.userId
          this.showdata.updateOrgId = this.user.orgInfo.orgId
          this.$http.put(url, this.showdata).then((res) => {
            if (res.data.status == '200') {
              data.route = '1';
              this.$http.get(Api.taskComplete, {params: data}).then((res) => {
                this.buttonloading1 = false;
                if (res.data.status == '200') {
                  this.$Message.success("审批成功")
                  this.returnTo();
                } else {
                  this.$Message.success("审批失败")
                }
              }).catch(e => {
                this.buttonloading1 = false;
                this.$Message.error("数据获取失败")
              })
            } else {
              this.buttonloading1 = false;
              console.log(res.data.msg)
            }

          }).catch(e => {
            this.buttonloading1 = false;
            this.$Message.error('请求失败');

          })


        } else {
          this.$Message.error('请检查填报数据!');
        }
      })
    },
    submit() {
      this.$refs['showdatas'].validate((valid) => {
        if (valid) {
          this.buttonloading1 = true;
          let data = {};
          data = {
            createUserId: this.user.userId,
            userName: this.user.userName,
            opinion: this.showdata.opinion,
            formKey: 'rectificationPlanForApproval',
            taskId: this.taskInfo.taskId,
            workId: this.taskInfo.workId,
            procinstId: this.taskInfo.procinstId,
            route: this.showdata.route
          };
          this.$http.get(Api.taskComplete, {params: data}).then((res) => {
            console.log(res)
            this.buttonloading1 = false;
            if (res.data.status == '200') {
              this.$Message.success("审批成功")
              this.returnTo();
            } else {
              this.$Message.success("审批失败")
            }
          }).catch(e => {
            this.buttonloading1 = false;
            this.$Message.error("数据获取失败")
          })


        } else {
          this.$Message.error('请填报完整!');
        }
      })
    },
    pageChange1(pageNum) {
      this.pageModel2.currentPage = pageNum;
      this.query();
    },
    selectContractor() {
      this.model2 = true
      this.contractor = []
      let data = {
        startPage: this.pageModel2.currentPage,
        size: this.pageModel2.pageSize,
        contractorName: this.pageModel2.contractorName
      }
      data = Object.assign(data);
      let url = Api.interestedPartiesAccountList
      this.$http.get(url, {params: data}).then((res) => {
        console.log(res.data);
        this.contractor = res.data.data.data;
        this.pageModel2.total = res.data.data.totalSize;
      }).catch(e => {
        this.$Message.error("数据获取失败")
      })
    },
    handleCancel() {
      this.showdata = {};
      this.$router.back();
    },
    formatDate(date, fmt) {
      if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
      }
      let o = {
        'M+': date.getMonth() + 1,
        'd+': date.getDate(),
        'h+': date.getHours(),
        'm+': date.getMinutes(),
        's+': date.getSeconds()
      };
      for (let k in o) {
        if (new RegExp(`(${k})`).test(fmt)) {
          let str = o[k] + '';
          fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? str : this.padLeftZero(str));
        }
      }
      return fmt;
    },
    padLeftZero(str) {
      return ('00' + str).substr(str.length);
    },
  },
}
</script>
<style lang='css' scoped>
@import '../../../index.css';

</style>
